var express = require('express');
var router = express.Router();
var ManagerModel = require('../models/manager');
var crypto = require('crypto');
router.get('/', function(req, res, next) {
  if(req.cookies.token){
    ManagerModel.find({token:req.cookies.token},function(err,data){
      if(data.length>0){
        res.redirect(302,'/manage');
      }else{
        res.render('login', { target:'index'});
      }
    })
  }else{
    res.render('login', { target:'index'});
  }
  
});
router.post('/', function(req, res, next) {
  var userInfo = req['body'];
  ManagerModel.find({"username":userInfo['username']},function(err,data){
    if (err) {
      return err;
    };
    if(data.length===0){
      return;
    }
    var user = data[0];
    if(user['password']===userInfo['password']){
      var sha1 = crypto.createHash('sha1');
      var token = sha1.update(Date.now().toString()+userInfo['username']).digest('hex');
      ManagerModel.update({username:userInfo["username"]},{$set:{token:token}},function(err,data){
        if (err) {
          return err;
        };
        console.log(data);
        res.cookie('token',token,{maxAge: 3600000});
        res.redirect(302,'/manage');
      });
      
    }else{
      res.redirect('/login');
    };
  });
});
module.exports = router;